package tech.yingchuan.blogs.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Service;
import tech.yingchuan.blogs.exception.ParamException;
import tech.yingchuan.blogs.util.StringUtils;
import tech.yingchuan.blogs.util.TimeUtils;

/**
 * ID生成器
 * @author YcDr 丁广义
 * @version 1.0
 * @date 2018/2/7
 */
@Service
public class SequenceServiceImpl implements SequenceService {

    @Autowired
    RedisConnectionFactory connectionFactory;

    @Override
    public String generate(String bizCode){
        /** 检查业务码 */
        boolean isLegal = isLegal(bizCode);
        if (!isLegal) {
            throw new ParamException("bizCode參数不合法");
        }
        /** 获取今天的日期:yyyyMMddHHmmss */
        String date = TimeUtils.getTodayTime();
        /** 构造redis的key */
        String key = SERIAL_NUMBER + bizCode;
        /** 自增 */
        long sequence = connectionFactory.getConnection().incr(key.getBytes());
        String seq = StringUtils.getSequence(sequence,5);
        StringBuilder sb = new StringBuilder();
        sb.append(date).append(bizCode).append(seq);
        String serial = sb.toString();
        return serial;
    }
}
